package com.gogowan.agroenterprise.supply;

import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CommodityInfo;
import com.gogowan.agroenterprise.model.CommodityOrderInfo;
import com.gogowan.agroenterprise.model.CommodityResultInfo;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.XmlInfos;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 确定下单后填写用户信息
 * @author Maniac
 * 2012.12.26
 */
public class OrderUserInfoActivity extends BaseActivity{
	
	private EditText person;
	private EditText phoneNum;
	private EditText address;
	private EditText goodsNum;
	private Button sendTime;
	private EditText others;
	private Button orderBtn;
	
	private ProgressDialog progressDialog;
	
	private SharedPreferences sharedPreferences;
	private long enterpriseId = 0;
	private long userId = 0;
	private CommodityInfo commodityInfo;
	private String date;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_commodity_order_userinfo);
		
		person = (EditText)findViewById(R.id.commodity_order_person);
		phoneNum = (EditText)findViewById(R.id.commodity_order_phonenum);
		address = (EditText)findViewById(R.id.commodity_order_address);
		goodsNum = (EditText)findViewById(R.id.commodity_order_goodsnum);
		sendTime = (Button)findViewById(R.id.commodity_order_sendtime);
		others = (EditText)findViewById(R.id.commodity_order_others);
		orderBtn = (Button)findViewById(R.id.commodity_order_commit);
		
		sharedPreferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = sharedPreferences.getLong("enterpriseid", 0);
		
		Intent intent = getIntent();
		String commodityDetail = intent.getStringExtra("commodityDetail");
		CommodityResultInfo commodityResultInfo = (CommodityResultInfo)Utils.fromJSON(commodityDetail, CommodityResultInfo.class);
		commodityInfo = commodityResultInfo.getCommodityInfo();
		
		String string = sharedPreferences.getString("saveLoginInfo", "");
		LoginResultInfo loginResultInfo = (LoginResultInfo)Utils.fromJSON(string, LoginResultInfo.class);
		userId = MyApplication.mSettings.getLong("personid",0);
		person.setText(MyApplication.mSettings.getString("username",""));
		
		orderBtn.setOnClickListener(orderBtnCallback);
		sendTime.setOnClickListener(dateBtnCallback);
	}

	public Button.OnClickListener orderBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			orderBtn.setEnabled(false);
			String personNameString = person.getText().toString().trim();
			String phoneNumString = phoneNum.getText().toString().trim();
			String addressString = address.getText().toString().trim();
			String goodsmunString = goodsNum.getText().toString().trim();
			String othersString = others.getText().toString().trim();
			
			//除备注外 其他不可为空
			if (personNameString == null || personNameString.equals("")) {
				showDialog("联系人不可为空");
				return;
			} else {
				if (phoneNumString == null || phoneNumString.equals("")) {
					showDialog("请填写您的联系方式");
					return;
				} else {
					if (addressString == null || addressString.equals("")) {
						showDialog("请填写您的送货地址");
						return;
					} else {
						if (goodsmunString == null || goodsmunString.equals("")) {
							showDialog("请填写您要订购的数量");
							return;
						} else {
							if (Long.parseLong(goodsmunString) >= Integer.MAX_VALUE) {
								showDialog("您填写订购数量的数字太大");
								return;
							}
							
							if (date == null || date.equals("")) {
								showDialog("请填写您的收货时间");
								return;
							} else {
								
								//未传折后总价和下单时间 orderPrice
								CommodityOrderInfo commodityOrderInfo = new CommodityOrderInfo();
								commodityOrderInfo.setAddress(addressString);
								commodityOrderInfo.setLinkMan(personNameString);
								commodityOrderInfo.setTelephone(phoneNumString);
								commodityOrderInfo.setOrderCount(Integer.parseInt(goodsmunString));
								commodityOrderInfo.setSaleTime(date);
								commodityOrderInfo.setRemark(othersString);
								commodityOrderInfo.setFwzs_Enterprise_ID(commodityInfo.getFromEnterpriseID());
								commodityOrderInfo.setFwzs_Enterprise_ID_From(enterpriseId);
								commodityOrderInfo.setFwzs_User_ID_From(userId);//下单人员id
								commodityOrderInfo.setSystemID(commodityInfo.getSystemID());
								commodityOrderInfo.setPrice_One(commodityInfo.getPrice_One());
								commodityOrderInfo.setRate(commodityInfo.getRate());
								
								XmlInfos xmlInfos = new XmlInfos();
								xmlInfos.setPrice_OneValue(String.valueOf(commodityInfo.getPrice_One()));
								xmlInfos.setUnitValue(commodityInfo.getUnit());
								xmlInfos.setPrice_RateValue(String.valueOf(commodityInfo.getRate_One()));
								xmlInfos.setOrderCountValue(goodsmunString);
								xmlInfos.setFWZS_Commodity_ID(String.valueOf(commodityInfo.getCommodityID()));
								xmlInfos.setUpdateCount(String.valueOf(commodityInfo.getUpdateCount()));
								
								commodityOrderInfo.setXmlInfo(xmlInfos);
								
								progressDialog = ProgressDialog.show(OrderUserInfoActivity.this,
										"提示",
										"正在提交订单信息,请稍候......", true, false);
								
								OrderAsyn orderAsyn = new OrderAsyn();
								orderAsyn.execute(commodityOrderInfo);
							}
						}
					}
				}
			}
			
		}
		
	};
	
	/**
	 * 提示有数据项没有填写的dialog
	 * @param string
	 */
	private void showDialog(String string){
    	new AlertDialog.Builder(OrderUserInfoActivity.this).setTitle("提示")
		.setMessage(string).setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				orderBtn.setEnabled(true);
			}
		}).create().show();
    }
	
	/**
	 * 下订单 异步操作
	 * @author Maniac
	 *	2012.12.26
	 */
	public class OrderAsyn extends MyAsyncTask{
		
		
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(OrderUserInfoActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(OrderUserInfoActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo)Utils.fromJSON(string, ResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 9110) {
						Toast.makeText(OrderUserInfoActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						OrderUserInfoActivity.this.finish();
						Utils.randomAnim(OrderUserInfoActivity.this);
					} else {
						Toast.makeText(OrderUserInfoActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			orderBtn.setEnabled(true);
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CommodityOrderInfo request = (CommodityOrderInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(9100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
	
	/**
	 * 时间选择按钮点击事件
	 */
	public Button.OnClickListener dateBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			showDialog(0);
		}
		
	};
	
	/**
     * 创建日期及时间选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
        switch (id) {
        case 0:
            Calendar c = Calendar.getInstance();
            dialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker dp, int year,int month, int dayOfMonth) {
                    	
                        Date curDate = new Date(System.currentTimeMillis());
                       /* int i = curDate.getYear() + 1900;
                        int j = curDate.getMonth() + 1;
                        int k = curDate.getDate();*/
                        if (year > (curDate.getYear() + 1900)) {
                        	sendTime.setText(year + "-" + (month+1) + "-" + dayOfMonth);
                            date = year + "-" + (month+1) + "-" + dayOfMonth;
						} else if (year == (curDate.getYear() + 1900)) {
							if ((month+1) > (curDate.getMonth() + 1)) {
								sendTime.setText(year + "-" + (month+1) + "-" + dayOfMonth);
	                            date = year + "-" + (month+1) + "-" + dayOfMonth;
							} else if ((month+1) == (curDate.getMonth() + 1)) {
								if (dayOfMonth >= curDate.getDate()) {
									sendTime.setText(year + "-" + (month+1) + "-" + dayOfMonth);
		                            date = year + "-" + (month+1) + "-" + dayOfMonth;
								} else {
									Toast.makeText(OrderUserInfoActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
								}
							} else {
								Toast.makeText(OrderUserInfoActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
							}
						} else {
							Toast.makeText(OrderUserInfoActivity.this, getString(R.string.date_error), Toast.LENGTH_LONG).show();
						}
                    }
                }, 
                c.get(Calendar.YEAR), // 传入年份
                c.get(Calendar.MONTH), // 传入月份
                c.get(Calendar.DAY_OF_MONTH) // 传入天数
            );
            break;
        }
		return dialog;
    	
    }
}
